package encrypt

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"errors"
)

const (
	DefaultKey = "default"
	APIKey     = "api"
)

var mapPublicKey map[string][]byte = map[string][]byte{
	DefaultKey: []byte(`-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD52nevs58WyF0gXO4oKCssiN7D
f/Fw5x/6z7Tno79Fs/iyz9QUxFdwZixLiMZ5PWdCk8939uu6BYmFxtGM8Ck95cFo
3RZGLbHQXq4fZ13sN/WzzxdFKxrHXSda9c2bp9mkDEm+adBrfDb7E12+PylGAutC
CsfgflXRufQA5An6hQIDAQAB
-----END PUBLIC KEY-----`),
	APIKey: []byte(`-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA82hi5YgKzh9JH1oa5qWz
lkghF/r8UBH8uMBCG9rIBG1eTNqXd4Bw6B2cOhH54UJ4lrCrh01aDvymNz43/mrG
ZM/22CaT9ITsD5QK84PNJrS3sxxN6ZVH+FI3e8xplzsz3aDxbb2i5xqcijo6ze/v
E7W1GOEy6jh2TuAlufz/WOLcI9KwWAVnj+SA3/7BYDW4S2LfSlLwo0JwBUZzENZo
2K2a4pJzpkqNLQxcXeoAHmDZC7n9Q/KZMP8FZuNIzffE9k/EtuYjDe40pjtl/b8m
ZalM5sgnfrPiS1YZXlm5nlf6IFAT/pM7GBBlNJ3FRwyXuyM4/9xKF0dqv+lvZ0YS
0QIDAQAB
-----END PUBLIC KEY-----`),
}

var mapPrivateKey map[string][]byte = map[string][]byte{
	DefaultKey: []byte(`-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQD52nevs58WyF0gXO4oKCssiN7Df/Fw5x/6z7Tno79Fs/iyz9QU
xFdwZixLiMZ5PWdCk8939uu6BYmFxtGM8Ck95cFo3RZGLbHQXq4fZ13sN/WzzxdF
KxrHXSda9c2bp9mkDEm+adBr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S4Yg5HDHMpnouSs
0eXCrHkCgYEAwLsSOCL20yfXF3rP4TUuO71q/YwXpFpIdVGxcZwbWC+rZTZIz29L
Q+dDAQEqYh6FTpjDBupC5Tje2Odx8SBUJROCCddsO4SNMmnpxC+pEpjKwZR0656T
VaZ0YMfWlUyYafqi6wdmoNhPMpxE8U+dVbpsx4b8av9+sTwYzVuu0nI=
-----END RSA PRIVATE KEY-----`),
}

// 使用公钥对数据进行加密
func RsaEncode(plain, key string) (string, error) {
	if key == "" || len(key) == 0 {
		key = DefaultKey
	}
	msg := []byte(plain)
	// 解码公钥
	pubBlock, _ := pem.Decode([]byte(mapPublicKey[key]))
	pubKeyValue, err := x509.ParsePKIXPublicKey(pubBlock.Bytes)
	if err != nil {
		return "", errors.New("publicKey error")
	}
	pub := pubKeyValue.(*rsa.PublicKey)
	encryptText, err := rsa.EncryptPKCS1v15(rand.Reader, pub, msg)
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(encryptText), nil
}

// 使用私钥对数据进行解密
func RsaDecode(strPlainText, key string) (string, error) {
	if key == "" || len(key) == 0 {
		key = DefaultKey
	}
	plainText, err := base64.StdEncoding.DecodeString(strPlainText)
	if err != nil {
		return "", err
	}
	bytePrivateKey := []byte(mapPrivateKey[key])
	// 解析私钥
	priBlock, _ := pem.Decode(bytePrivateKey)
	priKey, err := x509.ParsePKCS1PrivateKey(priBlock.Bytes)
	if err != nil {
		return "", err
	}
	decryptText, err := rsa.DecryptPKCS1v15(rand.Reader, priKey, plainText)
	if err != nil {
		return "", err
	}
	return string(decryptText), nil
}
